import { useRef, useState, useEffect } from "react";
import { Chart } from "@antv/g2";
import { Button } from "antd";

const MyHello = () => {
  // 类似于这种 chart 和 interval 这种，需要组件其他数据的更新不影响它。可以使用 useRef 来创建

  let chart: any = useRef(null);
  let interval: any = useRef(null);
  const boxRef = useRef(null);
  const [count, setCount] = useState(1);

  useEffect(() => {
    // 实例化
    chart.current = new Chart({
      container: boxRef.current as unknown as HTMLElement,
    });

    // 声明可视化
    interval.current = chart.current
      .interval() // 创建一个 Interval 标记
      .data([
        { genre: "Sports", sold: 275, age: 1 },
        { genre: "Strategy", sold: 115, age: 1 },
        { genre: "Action", sold: 120, age: 1 },
        { genre: "Shooter", sold: 350, age: 1 },
        { genre: "Other", sold: 150, age: 1 },
      ]) // 绑定数据

      .encode("x", "genre") // 编码 x 通道
      .encode("y", "age"); // 编码 y 通道

    // 渲染可视化
    chart.current.render();
  }, []);

  return (
    <div>
      <Button
        onClick={() => {
          setCount((count) => count + 1);
        }}
      >
        修改count {count}
      </Button>
      <Button
        onClick={() => {
          interval.current.data([{ genre: "Sports", sold: 275, age: 100 }]);

          chart.current.render();
        }}
      >
        修改图表
      </Button>
      <div className="box" ref={boxRef}></div>
    </div>
  );
};

export default MyHello;
